package com.apply.service;

import com.apply.config.utils.RandomUtil;
import com.apply.config.web.SidAuthContext;
import com.apply.entity.ApplyInfo;
import com.apply.entity.SysUser;
import com.apply.repository.ApplyRepository;
import com.apply.repository.ExamRepository;
import com.apply.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author tianp
 */
@Service
@Slf4j
public class ApplyService {
    @Autowired
    private ApplyRepository applyRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ExamRepository examRepository;
    @Autowired
    private AuthService authService;
    @Value("${image.path}")
    private String path;
    @Value("${ip.location}")
    private String location;

    @Transactional(rollbackFor = Exception.class)
    public void applyExam(ApplyInfo applyInfo, Long userId, Long examId) {
        applyInfo.setSysUser(userRepository.findOne(userId));
        applyInfo.setExamInfo(examRepository.findOne(examId));
        applyInfo.setApplyTime(new Date());
        applyInfo.setApplyId(RandomUtil.getRandom(4, 0, 9));
        applyRepository.save(applyInfo);
    }

    public Page<ApplyInfo> pageQuery(ApplyInfo applyInfo, PageRequest pageRequest) {
        return applyRepository.findAll(pageRequest);
    }

    @Transactional(rollbackFor = Exception.class)
    public String uploadFile(MultipartFile file, String sid) throws Exception {
        String filename = UUID.randomUUID() + "_" + file.getOriginalFilename();
        String filePath = path + filename;
        File img = new File(filePath);
        log.info("上传文件完整路径:{}", filePath);
        file.transferTo(img);
        StringBuilder sb = new StringBuilder(location);
        sb.append(filename);
        SysUser user = SidAuthContext.get();
        user.setPhotoPath(sb.toString());
        userRepository.updateUser(sb.toString(), user.getId());
        authService.remove(sid, user);
        return sb.toString();
    }

    public List<ApplyInfo> findBySysUserId(Long id) {
        return applyRepository.findBySysUserId(id);
    }

    public Boolean canApply(Long examId, Long sysUserId) {
        int total = applyRepository.countByExamInfoIdAndSysUserId(examId, sysUserId);
        return total < 1;
    }
}
